//package com.dlc.felear.xiaoensale.deviceControlSf;
//
//import android.os.Handler;
//import android.os.Message;
//import android.text.TextUtils;
//import android.util.Log;
//
//import com.dlc.felear.xiaoensale.constant.Constant;
//import com.dlc.felear.xiaoensale.dlc_serial_port.DlcSerialPortClient;
//import com.dlc.felear.xiaoensale.entity.Operator;
//import com.dlc.felear.xiaoensale.entity.TiaoLiaoInfo;
//import com.dlc.felear.xiaoensale.factory.CmdList;
//import com.dlc.felear.xiaoensale.helper.JsonHelper;
//import com.dlc.felear.xiaoensale.utils.HexUtil;
//
//import java.util.HashMap;
//import java.util.Map;
//import java.util.concurrent.ThreadPoolExecutor;
//
//public class TiaoliaoControl implements Handler.Callback {
//    private static final String TAG = "TiaoliaoControl";
//    private static final int WHAT_DELAY_CLOSE_IO = 8215;
//    private static final int WHAT_DELAY_GT = 8117;
//    private String serialNum;
//    private int gtPosition = GuotiActionControl.POSITION_3;
//    private Map<Integer, TiaoLiaoInfo> cacheCmds = new HashMap<>();
//    private ThreadPoolExecutor scheduledThreadPool;
//    private int chuifengio = 21;
//    private int qzjbio = 23;
//    private int choufengio = 20;
//    private int DV = 65535;
//    private boolean ccFlag = false;
//    private Handler handler;
//    private OperatorAutoHandle operatorAutoHandle;
//    private String deviceType = "M400";
//
//    public TiaoliaoControl(String serialNum,
//                           ThreadPoolExecutor scheduledThreadPool) {
//        this.serialNum = serialNum;
//        this.scheduledThreadPool = scheduledThreadPool;
//        setXpLqStatus(0xFF);
//        sendCmd(CmdList.handShade());
//        handler = new Handler(this);
//    }
//
//    public void setDeviceType(String deviceType) {
//        this.deviceType = deviceType;
//    }
//
//    public void setOperatorAutoHandle(OperatorAutoHandle operatorAutoHandle) {
//        this.operatorAutoHandle = operatorAutoHandle;
//    }
//
//
//    public void setOperator(Operator operator) {
//        log("deviceType:" + deviceType + " operator:" + JsonHelper.toJson(operator));
//        switch (operator.getName()) {
//            case Constant.ACTION_NAME_HHJY:
//            case Constant.ACTION_NAME_GQZ:
//            case Constant.ACTION_NAME_YTJJ:
//            case Constant.ACTION_NAME_LAOCHOU:
//            case Constant.ACTION_NAME_HONGYOU:
//            case Constant.ACTION_NAME_YOU:
//            case Constant.ACTION_NAME_SHUI:
//            case Constant.ACTION_NAME_SHUI1:
//                jttlByllj(operator);
//                break;
//            case Constant.ACTION_NAME_JLA:
//                jttlByTime(operator);
//                break;
//        }
//    }
//
//    private void jttlByllj(Operator operator) {
//        if (operator.getValue() != 0) {
//            controlYttlByPlus(operator.getNum(), operator.getValue());
//            log("controlYttlByPlus 脉冲数:" + operator.getValue());
//        } else {
//            float msec = operatorAutoHandle.mlVavluechange(operator.getName(), operator.getValue1());
//            log("controlYttlByPlus 换算脉冲数:" + msec);
//            controlYttlByPlus(operator.getNum(), (int) msec);
//            handlerTimeOut(operator);
//        }
//    }
//
//
//    private void normalYttl(int num, int msec) {
//        int sec = msec / 1000;
//        log("normalYttl num:" + num + " 打开时间:" + sec);
//        sendCmd(CmdList.OpenDO(num, sec + 1));
//    }
//
//
//    private void handlerTimeOut(Operator operator) {
//        if (!ccFlag) {
//            return;
//        }
//        int delay = operatorAutoHandle.mlVavluechangeMsec(operator.getName(), operator.getValue1());
//        if (operator.getValue1() > 500) {
//            delay = 2 * delay;
//        } else {
//            delay = (int) (1.5f * delay);
//        }
//        log(delay + "秒后关闭");
//    }
//
//    private void controlYttlByPlus(int num, int plus) {
//        log("ccFlag=" + ccFlag);
//        int falg = (plus == 0 ? 0 : 1);
//        int s1 = getBs(plus);
//        int s2 = (int) Math.ceil(plus / s1);
//        sendCmd(CmdList.setLljPlus(num, s2, s1, falg));
//        log("加液体调料2: num=" + num + " plus=" + plus + " dv:" + s1 +
//                " totalplus=" + s1 * s2 + " flag=" + falg);
//    }
//
//    private int getBs(int plus) {
//        int temp = plus / DV;
//        if (temp <= 0) {
//            temp = 1;
//        }
//        return temp;
//    }
//
//
//    private void sendCmd(byte[] data) {
//        log("data:" + HexUtil.bytes2HexString(data));
//        DlcSerialPortClient.getInstance().send(serialNum, data);
//    }
//
//    /**
//     * 操作固体调料鼓风
//     *
//     * @param value
//     */
//    public void setXpLqStatus(int value) {
//        log("固体风机：" + value);
//        sendCmd(CmdList.OpenDO(qzjbio, value));
//        sendCmd(CmdList.OpenDO(chuifengio, value));
//    }
//
//    /**
//     * 操作抽风DO
//     *
//     * @param value
//     */
//    public void setChoufengStatus(int value) {
//        log("抽风:" + value);
//        if (value > 0) {
//            value = 255;
//        }
//        setXpLqStatus(value);
//        sendCmd(CmdList.OpenDO(choufengio, value));
//    }
//
//
//    private void log(String msg) {
//        if (!TextUtils.isEmpty(msg)) {
//            Log.e(TAG, msg);
//        }
//    }
//
//    /**
//     * @param flag f炒菜结束 t炒菜开始
//     */
//    public void isChaocaiStatus(boolean flag) {
//        ccFlag = flag;
//        if (!flag) {
//            cacheCmds.clear();
//        }
//    }
//
//    private void jttlByTime(Operator operator) {
//        if (operator.getValue() != 0) {
//            normalYttl(operator.getNum(), operator.getValue() * 1000);
//        } else {
//            int temp = operatorAutoHandle.mlVavluechangeMsec(operator.getName(), operator.getValue1());
//            normalYttl(operator.getNum(), temp);
//        }
//    }
//
//
//    @Override
//    public boolean handleMessage(Message message) {
//        if (message.what == WHAT_DELAY_CLOSE_IO + message.arg1) {
//            log("超时关闭:" + message.arg1);
//            sendCmd(CmdList.OpenDO(message.arg1, 0x00));
//        }
//        return false;
//    }
//
//
//    /**
//     * 延迟发送关闭IO的指令
//     *
//     * @param mSec
//     * @param id
//     * @param num
//     */
//    private void handleDelayClose(int mSec, int id, int num) {
//        log("延迟关闭DO:" + num + " delay:" + mSec);
//        int waht = WHAT_DELAY_CLOSE_IO + num;
//        handler.removeMessages(waht);
//        Message message = Message.obtain();
//        message.what = waht;
//        message.arg1 = num;
//        message.arg2 = id;
//        handler.sendMessageDelayed(message, mSec);
//    }
//
//
//}

package com.dlc.felear.xiaoensale.deviceControlSf;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.dlc_serial_port.DlcSerialPortClient;
import com.dlc.felear.xiaoensale.entity.Operator;
import com.dlc.felear.xiaoensale.entity.TiaoLiaoInfo;
import com.dlc.felear.xiaoensale.factory.CmdList;
import com.dlc.felear.xiaoensale.helper.JsonHelper;
import com.dlc.felear.xiaoensale.utils.HexUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

public class TiaoliaoControl implements Handler.Callback {
    private static final String TAG = "TiaoliaoControl";
    private static final int WHAT_DELAY_CLOSE_IO = 8215;
    private static final int WHAT_DELAY_GT = 8117;
    private String serialNum;
    private int gtPosition = GuotiActionControl.POSITION_3;
    private GuotiActionControl guotiActionControl;
    private Map<Integer, TiaoLiaoInfo> cacheCmds = new HashMap<>();
    private int chuifengio = 21;
    private int choufengio = 20;
    private int DV = 65535;
    private boolean ccFlag = false;
    private Handler handler;
    private OperatorAutoHandle operatorAutoHandle;
    private String deviceType = "M400";

    public TiaoliaoControl(String serialNum, GuotiActionControl guotiActionControl) {
        this.serialNum = serialNum;
        this.guotiActionControl = guotiActionControl;
//        if (TextUtils.equals(deviceType,"M600")) {
//            setXpLqStatus(0xFF);
//        }
        sendCmd(CmdList.handShade());
        handler = new Handler(this);
    }

    public void setDeviceType(String deviceType) {
        this.deviceType = deviceType;
    }

    public void setOperatorAutoHandle(OperatorAutoHandle operatorAutoHandle) {
        this.operatorAutoHandle = operatorAutoHandle;
    }


    public void setOperator(Operator operator) {
        log("deviceType:" + deviceType + " operator:" + JsonHelper.toJson(operator));
        switch (operator.getName()) {
            case Constant.ACTION_NAME_HHJY:
            case Constant.ACTION_NAME_GQZ:
            case Constant.ACTION_NAME_YTJJ:
            case Constant.ACTION_NAME_LAOCHOU:
            case Constant.ACTION_NAME_HONGYOU:
            case Constant.ACTION_NAME_YOU:
            case Constant.ACTION_NAME_SHUI:
                jttlByllj(operator);
                break;
            case Constant.ACTION_NAME_JLA:
                jttlByTime(operator);
                break;
        }
    }

    private void jttlByllj(Operator operator) {
        if (operator.getValue() != 0) {
            controlYttlByPlus(operator.getNum(), operator.getValue());
            log("jttlByllj 脉冲数:" + operator.getValue());
        } else {
            float msec = operatorAutoHandle.mlVavluechange(operator.getName(), operator.getValue1());
            log("jttlByllj 调料重量:"+operator.getName()+"调料量:"+operator.getValue1()+" 换算脉冲数:" + msec);
            controlYttlByPlus(operator.getNum(), (int) msec);
            handlerTimeOut(operator);
        }
    }

    private void jttlByTime(Operator operator) {
        log("jttlByTime:"+JsonHelper.toJson(operator));
        if (operator.getValue() != 0) {
            normalYttl(operator.getNum(), operator.getValue() * 1000);
        } else {
            int temp = operatorAutoHandle.mlVavluechangeMsec(operator.getName(), operator.getValue1());
            normalYttl(operator.getNum(), temp);
        }
    }

    private void normalYttl(int num, int msec) {
        int sec = msec / 1000;
        log("normalYttl num:" + num + " 打开时间:" + sec);
        sendCmd(CmdList.OpenDO(num, sec + 1));
        handleDelayClose(msec, 0, num);
    }


    private void handlerTimeOut(Operator operator) {
        if (!ccFlag) {
            return;
        }
        int delay = operatorAutoHandle.mlVavluechangeMsec(operator.getName(), operator.getValue1());
        if (operator.getValue1() > 500) {
            delay = 2 * delay;
        } else {
            delay = (int) (1.5f * delay);
        }
        log(delay + "秒后关闭");
        handleDelayClose(delay, 0, operator.getNum());
    }

    private void controlYttlByPlus(int num, int plus) {
        log("ccFlag=" + ccFlag + " checkYttlP=" + guotiActionControl.checkYttlP());
        if (!ccFlag) {
            int falg = (plus == 0 ? 0 : 1);
            int s1 = getBs(plus);
            int s2 = (int) Math.ceil(plus / s1);
            log("加液体调料2: num=" + num + " plus=" + plus + " dv:" + s1 +
                    " totalplus=" + s1 * s2 + " flag=" + falg);
            sendCmd(CmdList.setLljPlus(num, s2, s1, falg));
            return;
        }
        if (ccFlag && !guotiActionControl.checkYttlP()) {
            log("锅不在加调料位置");
            guotiActionControl.runPositionCc(guotiActionControl.getCcLevelPosition());
            saveCacheCmd(num, plus, 0);
            return;
        }
        cacheCmds.remove(num);
        int falg = (plus == 0 ? 0 : 1);
        int s1 = getBs(plus);
        int s2 = (int) Math.ceil(plus / s1);
        log("加液体调料2: num=" + num + " plus=" + plus + " dv:" + s1 +
                " totalplus=" + s1 * s2 + " flag=" + falg);
        sendCmd(CmdList.setLljPlus(num, s2, s1, falg));
    }

    private int getBs(int plus) {
        int temp = plus / DV;
        if (temp <= 0) {
            temp = 1;
        }
        return temp;
    }


    /**
     * 缓存指令信息
     *
     * @param num
     * @param mSec
     * @param id
     */
    private void saveCacheCmd(int num, int mSec, int id) {
        cacheCmds.put(num, new TiaoLiaoInfo(num, id, mSec));
    }


    private void sendCmd(byte[] data) {
//        log("data:" + HexUtil.bytes2HexString(data));
        DlcSerialPortClient.getInstance().send(serialNum, data);
    }

    /**
     * 操作固体调料鼓风
     *
     * @param value
     */
    public void setXpLqStatus(int value) {
        log("固体风机：" + value);
        sendCmd(CmdList.OpenDO(chuifengio, value));
    }

    /**
     * 操作抽风DO
     *
     * @param value
     */
    public void setChoufengStatus(int value) {
        log("抽风:" + value);
//        if (TextUtils.equals(deviceType,"M400")) {
//            setXpLqStatus(value);
//        }else {
//            setXpLqStatus(255);
//        }
        if(value<=0){
            value=0;
        }else {
            value=255;
        }
        setXpLqStatus(value);
        sendCmd(CmdList.OpenDO(choufengio, value));
    }

    /**
     * 监听IO状态
     *
     * @param num
     */
    public void gtStatus(int num) {
        log("posion=" + num + " gtPosition=" + gtPosition);
        boolean flag = (num == GuotiActionControl.POSITION_4 || num == GuotiActionControl.POSITION_5 ||
                num == GuotiActionControl.POSITION_6 || num == GuotiActionControl.POSITION_6);
        if (ccFlag && flag) {
            pactCmd();
        } else {
            cacheCmds.clear();
        }
    }

    /**
     * 分发缓存的操作指令
     */
    public void pactCmd() {
        log("cacheCmds=" + JsonHelper.toJson(cacheCmds));
        if (cacheCmds.isEmpty()) {
            return;
        }
        for (Integer num : cacheCmds.keySet()) {
            TiaoLiaoInfo tiaoLiaoInfo = cacheCmds.get(num);
            controlYttlByPlus(tiaoLiaoInfo.getNum(), tiaoLiaoInfo.getmSce());
            cacheCmds.remove(num);
        }

    }

    private void log(String msg) {
        if (!TextUtils.isEmpty(msg)) {
            Log.e(TAG, msg);
        }
    }

    /**
     * @param flag f炒菜结束 t炒菜开始
     */
    public void isChaocaiStatus(boolean flag) {
        ccFlag = flag;
        if (!flag) {
            cloase();
            cacheCmds.clear();
        }
    }

    private void cloase(){
        for (int i = 1; i <13 ; i++) {
            sendCmd(CmdList.OpenDO(i,0));
        }
    }


    @Override
    public boolean handleMessage(Message message) {
        if (message.what == WHAT_DELAY_CLOSE_IO + message.arg1) {
            log("超时关闭:" + message.arg1);
            sendCmd(CmdList.OpenDO(message.arg1, 0x00));
        } else if (message.what == WHAT_DELAY_GT) {
            if (ccFlag) {
                guotiActionControl.runPositionCc(guotiActionControl.getCcLevelPosition());
            }
        }
        return false;
    }


    /**
     * 延迟发送关闭IO的指令
     *
     * @param mSec
     * @param id
     * @param num
     */
    private void handleDelayClose(int mSec, int id, int num) {
        log("延迟关闭DO:" + num + " delay:" + mSec);
        int waht = WHAT_DELAY_CLOSE_IO + num;
        handler.removeMessages(waht);
        Message message = Message.obtain();
        message.what = waht;
        message.arg1 = num;
        message.arg2 = id;
        handler.sendMessageDelayed(message, mSec);
    }


}

